# -*- coding=utf-8 -*-
import time
import hashlib
from .app_config import AppConfig
from . import error


class Utils(AppConfig):

    @classmethod
    def treated_params(cls, params):
        """
        处理请求参数
        :param params: 请求参数
        :return: 返回请求参数
        """
        signature_params = {}
        for key, value in params.items():
            if value or value == 0:
                signature_params[key] = value
        return cls.__generate_params(params, signature_params)

    @classmethod
    def __generate_params(cls, params, signature_params):
        """
        生成请求参数
        :param params: 请求参数
        :param signature_params: 签名参数
        :return: 返回签名后的参数
        """
        params["mchNo"] = signature_params["mchNo"] = AppConfig._get_mch_no()
        params["appId"] = signature_params["appId"] = AppConfig._get_app_id()
        params["reqTime"] = signature_params["reqTime"] = int(round(time.time() * 1000))
        params["version"] = signature_params["version"] = AppConfig._get_version()
        params["signType"] = signature_params["signType"] = "MD5"
        params["sign"] = cls._signature_rules(signature_params)
        return params

    @classmethod
    def _signature_rules(cls, signature_params):
        """
        签名规则
        :param signature_params: 签名的参数
        :return: 返回签名值
        """
        try:
            temp_data = sorted(signature_params.items(), key=lambda x: x[0], reverse=False)
            text = ""
            for key, value in dict(temp_data).items():
                text += f"{key}={value}&"
            text += f"key={AppConfig._get_api_key()}"
        except Exception as e:
            raise error.RequestError(e)
        else:
            return cls.__md5_encrypt(text)

    @staticmethod
    def __md5_encrypt(text):
        md5 = hashlib.md5()
        md5.update(text.encode("utf-8"))
        return md5.hexdigest().upper()
